export const useCache = <T>(cacheMap: CacheMap<T>, key: string, force: boolean, fetch: () => Promise<T>, expire: number = 60): Promise<T> => {
    const cache = cacheMap.get(key);
    if (!force && cache) return Promise.resolve(cache);
    return fetch().then(res => {
        cacheMap.set(key, res)
        return res
    })
}
const now = () => Math.floor(Date.now() / 1000);

export class CacheMap<T> {
    readonly dataMap = new Map<string, T>();
    readonly timeMap = new Map<string, number>();

    set = (key: string, value: T) => {
        this.dataMap.set(key, value);
        this.timeMap.set(key, now());
    }

    delete = (key: string) => {
        this.dataMap.delete(key);
        this.timeMap.delete(key);
    }

    /**
     * 获取缓存，如果过期则返回undefined
     * @param key 缓存的key
     * @param expire 过期时间，单位为秒
     */
    get = (key: string, expire: number = 60): T | undefined => {
        const time = this.timeMap.get(key);
        if (!time) return undefined;
        if (now() - time > expire) {
            this.delete(key);
            return undefined;
        }
        return this.dataMap.get(key);
    }

}